<template>
<view>
		<view class="head">
			<navigator @click="gotoarrow" class="return-arrow">
				<image class="return-img" src="../../../../static/arrow.png"></image>
			</navigator>
			<view class="service-list">预约详情</view>
		</view>
		<view class="list">
			<img class="img-avatar" :src="reservation_detail.service_img" >
			<p class="nane"><span class="title-left">服务卡项:</span>{{reservation_detail.cardName}}</p>
			<p class="nane"><span class="title-left">服务项目:</span>{{reservation_detail.serviceTitles}}</p>
			<p class="nane" v-if="type=='edit'"><span class="title-left">用户名:</span> <input type="text" maxlength="200" v-model="userName" class="van-field_control"></p>
			<p class="nane" v-if="type=='edit'"><span class="title-left">预约手机号:</span> <input type="text" maxlength="200" v-model="userPhone" class="van-field_control"></p>
			<p class="nane" v-if="type=='edit'"><span class="title-left">预约位数:</span> <input type="text" maxlength="200" v-model="userCount" class="van-field_control"></p><button class="appointment" v-if="reservation_detail.status==0 && type=='edit'"  @click="update_reserve(reservation_detail.id,'edit')">修改</button>
			<p class="nane" v-if="type!='edit'"><span class="title-left">用户名:</span> {{reservation_detail.userName}}</p>
			<p class="nane" v-if="type!='edit'"><span class="title-left">预约手机号:</span> {{reservation_detail.userPhone}}</p>
			<p class="nane" v-if="type!='edit'"><span class="title-left">预约位数:</span> {{reservation_detail.userCount}}</p>
			<p class="nane"><span class="title-left">预约类型:</span> {{reservation_detail.froms}}</p>
			<p class="nane"><span class="title-left">美容师:</span> {{reservation_detail.shopUserName}}</p>
			<button class="appointment" v-if="reservation_detail.status==0 && reservation_detail.serviceStartTime!=null"  @click="update_reserve(reservation_detail.id,'end')">完成服务</button>
			<button class="appointment" v-if="reservation_detail.status==0 && reservation_detail.serviceStartTime==null && reservation_detail.serviceDate==cur_day" @click="update_reserve(reservation_detail.id,'start')">开始服务</button>
				<button class="appointment2" v-if="reservation_detail.status==1">已使用</button>
				<button class="appointment2" v-if="reservation_detail.status==2">已过期</button>
				<p class="time"><span class="title-left">预约时间:</span> {{reservation_detail.serviceDate}} <br>{{reservation_detail.serviceHours}}</p>
				<p class="time"  v-if="reservation_detail.status==1"><span class="title-left">服务时间:</span> <br />{{reservation_detail.serviceStartTime}}~{{reservation_detail.serviceEndTime}}</p>
				<view class="ref-img-list"  v-if="type!='edit'">
					  <div v-if="reserve_img_before.length > 0">
						<p class="nane service-continue-upload">
						  <span class="title-left" style="flex:1;">服务前图片:</span>
						  <button class="upload-btn upload-continue" @click="uploadImg(reservation_detail.id,'start')">继续上传</button>
						</p>
						  <div class="picBoxShow">
								<imgsBanner :imgList='reserve_img_before' :currentImg='currentImg' @del="delReImgUrl"></imgsBanner>
						  </div>
						   
					  </div>
					  <div v-else>
						 <p class="nane"><span class="title-left">服务前图片:</span></p>
						 <div class="no-img">
							 <div class="no-img-title">暂未上传图片</div>
							 <button class="upload-btn" @click="uploadImg(reservation_detail.id,'start')">去上传</button>
						 </div>
					  </div>
					
					  <div v-if="reserve_img_after.length > 0">
						<p class="nane service-continue-upload" style="margin-top: 10px;">
						   <span class="title-left" style="flex:1;">服务后图片:</span>
						   <button class="upload-btn upload-continue" @click="uploadImg(reservation_detail.id,'end')">继续上传</button>
						 </p>
						  <div class="picBoxShow">							
								<imgsBanner :imgList='reserve_img_after' :currentImg='currentImg' @del="delReImgUrl"></imgsBanner>
						  </div>
					  </div>
					  <div v-else>
						<p class="nane" style="margin-top: 10px;"><span class="title-left">服务后图片:</span></p>
						<div class="no-img" style="margin-top: 10px;">
							 <div class="no-img-title">暂未上传图片</div>
							 <button class="upload-btn" @click="uploadImg(reservation_detail.id,'end')">去上传</button>
						</div>
					  </div>
				</view>
		</view>
		<popup :open="openFile" :position="position" :percent="percent" :background="background" @close="closeFile" class="popup-file">
			<view class="pop-detail">
				  <div class="upload-info">
					  <text class="title_info">{{title_info}}</text>
					<div>
					<view v-for="pic in filePath"  class="picBox">
						<view class="remove-pic"  @click="removePic(pic)">X</view>
						<img class="pic-box" :src="pic">						
					</view>
					</div>
					<div style="clear: both;">
					<button type="primary" :loading="loading" @click="qupload">选择图片</button>
					<button type="primary" :loading="loading" @click="qsubmit">提交</button>
					<button type="info" @click="closeFile" style="background: #333 !important;">暂不上传</button>
					</div>
				  </div>
			</view>
		</popup>
</view>
</template>

<script>
import util from '@/common/util.js';
import popup from '@/components/YYT-popup/YYT-popup.vue';
import qiniuUploader from '@/components/qiniuUploader/qiniuUploader.js';
 import imgsBanner from '@/components/imgsBanner-tag/imgsBanner-tag.vue'
//import Vue from 'vue'
//import * as qiniu from 'qiniu-js';
//import ElementUI from 'element-ui' //element-ui的全部组件
//import 'element-ui/lib/theme-chalk/index.css'//element-ui的css
//Vue.use(ElementUI) //使用elementUI
export default {
	components: {
		popup,qiniuUploader,imgsBanner
	},
	data() {
	  return {
		reservation_detail:[],
		reserve_list:[],
		userName:"",
		userPhone:"",
		userCount:"",
		type:"",
	    openPopup: false,
	    position: '',
	    background: '#fff',
	    openAdPopup: false,
		openFile:false,
	    percent: 0,
		cur_day:(new Date()).Format("yyyy-MM-dd"),
	    showText: false,
	    change: false,
	    loopTimer: false,
	    sizeSort: 'asc',
		reserve_img_before:[],
		reserve_img_after:[],
		loading: false,
		key: [], //图片名字处理
		token: [], //七牛云token
		domain: "https://upload-z2.qiniup.com", // 七牛云的上传地址（华南区）
		qiniuaddr: "http://images.common.think1st.cn", // 七牛云的图片外链地址
		uploadPicUrl: "", //提交到后台图片地址
		fileList: [],
		limit:5,
		rlId:'',
		imgType:'',
		title_info:'',
		filePath: [],
		currentImg:0,  //当前默认选中
	  }
	},
	props: {
			cardName: {
				type: String
			},
			cardId: {
				type: Number
			},
			status: {
				type: Number
			},
		},
	onLoad(event) {
		this.reservation_detail=JSON.parse(event.reservation_data);
		this.type=event.type;
		this.userName=this.reservation_detail.userName!=null ? this.reservation_detail.userName:"";
		this.userPhone=this.reservation_detail.userPhone!=null ? this.reservation_detail.userPhone:"";
		this.userCount=this.reservation_detail.userCount!=null ? this.reservation_detail.userCount:"";
		this.getRefImg();
	},
	methods:{
		removePic(pic){
			var filePathNew=[]
			for (var i = 0; i < this.filePath.length; i++) {
				if(pic!=this.filePath[i]){
					filePathNew.push(this.filePath[i]);
				}
			}
			this.filePath=filePathNew;
		},
		qupload() {
			// 选择图片
			uni.chooseImage({
				count: 4,
				success: (res) => {
					this.filePath = this.filePath.concat(res.tempFilePaths);
					console.log(this.filePath);
					for (var i = 0; i < this.filePath.length; i++) {
						uni.request({
							url: 'https://emedia.sbedian.com/api/ability/getQiniuTokenInfo/common/ami_service',
							method: 'GET',
							header:{'content-type': 'application/x-www-form-urlencoded'},
							complete: (result) => {
								let tokenData = result.data;
								if (tokenData.code == "1") {
									this.token.push(tokenData.data.token);
									this.key.push(tokenData.data.name);
								}
							},
						});
					
					}
				}
			});
			
		},
		qsubmit() {//循环上传图片
			for (var i = 0; i < this.filePath.length; i++) {
				
				qiniuUploader.upload(this.filePath[i], (res) => {
					 this.addimgUrl(res.imageURL);
					console.log(res.imageURL);
				}, (error) => {
					var a = JSON.stringify(error);
					console.log('error: ' + a);
				}, {
					region: 'ECN',
					domain: this.qiniuaddr, // // bucket 域名，下载资源时用到。如果设置，会在 success callback 的 res 参数加上可以直接使用的 ImageURL 字段。否则需要自己拼接
					key: this.key[i], // [非必须]自定义文件 key。如果不设置，默认为使用微信小程序 API 的临时文件名
					// 以下方法三选一即可，优先级为：uptoken > uptokenURL > uptokenFunc
					uptoken: this.token[i],
				});
			}
		},
		gotoarrow(){
			this.$router.go(-1)
		},
		update_reserve(cid,type){
			var params={};
			if(type=='start'){
				params={id:cid,serviceStartTime:(new Date()).Format("yyyy-MM-dd hh:mm:ss")};
			}else if(type=='end'){
				params={id:cid,serviceEndTime:(new Date()).Format("yyyy-MM-dd hh:mm:ss"),status:1};
			}else if(type=='edit'){
				params={id:cid,userName:this.userName,userPhone:this.userPhone,userCount:this.userCount};
			}
			uni.request({
				url: uni.getStorageSync('api_url')+'/reserve/update',
				method: 'POST',
				data:params,
				header:{'content-type': 'application/x-www-form-urlencoded'},
				complete: (result) => {
					uni.hideLoading();
					if(result.data.code != 1){
						uni.showToast({
							title:result.data.msg,
							icon:'none'
						});
					}else{
						uni.showToast({
							title:result.data.msg,
						});
					}
					
				},
			});
		},
		getRefImg(){
			uni.showLoading();
			uni.request({
				url: uni.getStorageSync('api_url')+'/reserve/getRefImgList?rlId='+this.reservation_detail.id,
				complete: (result) => {						
					if(result.data.code != 1){
						uni.hideLoading();
						uni.showToast({
							title:result.data.msg,
							icon:'none'
						});
					}else{
						uni.hideLoading();
						const data=result.data.data.data;				
						this.reserve_img_after=[];
						this.reserve_img_before=[];	
						data.forEach((rst) => {
							if(rst.type=="end"){
								this.reserve_img_after.push(rst);	
							}else{
								this.reserve_img_before.push(rst);
							}
						});	
						
					}						
				},
			});
		},
		closeFile(){
			this.openFile=false;
			this.uploadPicUrl = '';
		},
		uploadImg(rid,type){
			this.position = 'ad';
			this.openFile =true;
			this.filePath=[];
			this.imgType=type;
			this.rlId = rid;
			if(type=='start'){
				this.title_info = '上传服务前的图片:'
			}else{
				this.title_info = '上传服务后的图片:'
			}
			//this.getQiniuToken();
		},
		handleRemove(file, fileList) {
		  this.uploadPicUrl = "";
		},
		handleExceed(files, fileList) {
		  this.$message.warning("当前限制选择"+this.limit+"张图片，如需更换，请删除上一张图片在重新选择!");
		},
		beforeAvatarUpload(file) {
		//	this.getQiniuToken();
		  const isPNG = file.type === "image/png";
		  const isJPEG = file.type === "image/jpeg";
		  const isJPG = file.type === "image/jpg";
		  const isLt2M = file.size / 1024 / 1024 < 2;
			
		  if (!isPNG && !isJPEG && !isJPG) {
			this.$message.error("上传图片只能是 jpg、png、jpeg 格式!");
			return false;
		  }
		  if (!isLt2M) {
			this.$message.error("上传图片大小不能超过 2MB!");
			return false;
		  }
		  //this.getQiniuToken();
		  //console.log(`upload_pic_${file.name}`);
		  //this.QiniuData.key = 'ami_service/'+`upload_pic_${file.name}`;
		},
		uploadSuccess(response, file, fileList) {
		  //console.log(fileList);
		  this.uploadPicUrl = `${this.qiniuaddr}/${response.key}`;
		  var uploadPicUrl = `${this.qiniuaddr}/${response.key}`;
		  this.addimgUrl(uploadPicUrl);
		  
		},
		uploadError(err, file, fileList) {
		  this.$message({
			message: "上传出错，请重试！",
			type: "error",
			center: true
		  });
		},
		beforeRemove(file, fileList) {
		  // return this.$confirm(`确定移除 ${ file.name }？`);
		},
		//提交数据到后台
		handleSubmit() {
			 this.$refs.upload.submit();
		},
		addimgUrl(uploadPicUrl){
			uni.request({
				url: uni.getStorageSync('api_url')+'/reserve/addReImgUrl',
				method: 'POST',
				header:{'content-type': 'application/x-www-form-urlencoded'},
				data:{rlId:this.rlId,type:this.imgType,plUrl:uploadPicUrl,createUser:uni.getStorageSync('admin_name'),shoperId:uni.getStorageSync('admin_id'),shopId:uni.getStorageSync('shop_id')},
				complete: (result) => {					
					if(result.data.code!='1'){
						uni.showToast({
							title:result.data.msg,
							icon:'none'
						});
					}else{
						uni.showToast({
							title:'图片上传成功',
							icon:'none'
						});
						this.openFile=false;
						this.uploadPicUrl = '';
					}
					this.getRefImg();
					location.reload();
				},
			});	
		},
		delReImgUrl(item){
			var _this=this;
			uni.showModal({
			    title: '确认',
			    content: '删除图片后无法恢复，确定要删除吗',
			    success: function (res) {
			        if (res.confirm) {
			            var plFile=item.plUrl.replace(this.qiniuaddr+'/','');
			            uni.request({
			            	url: uni.getStorageSync('api_url')+'/reserve/delReImgUrl',
			            	method: 'POST',
			            	header:{'content-type': 'application/x-www-form-urlencoded'},
			            	data:{plId:item.plId,plFile:plFile,admin_code:uni.getStorageSync('admin_code')},
			            	complete: (result) => {					
			            		if(result.data.code!='1'){
			            			uni.showToast({
			            				title:result.data.msg,
			            				icon:'none'
			            			});
			            		}else{
			            			uni.showToast({
			            				title:'图片删除成功',
			            				icon:'none'
			            			});
									　location.reload(); 
			            			//_this.getRefImg();
			            		}
			            		
			            	},
			            });	
			        }
			    }
			});
		},
		//请求后台拿七牛云token
		getQiniuToken() {
			uni.request({
				url: 'https://emedia.sbedian.com/api/ability/getQiniuTokenInfo/common/ami_service',
				method: 'GET',
				header:{'content-type': 'application/x-www-form-urlencoded'},
				complete: (result) => {
					let tokenData = result.data;
					if (tokenData.code == "1") {
						this.QiniuData.token = tokenData.data.token;
						this.QiniuData.key = tokenData.data.name;
						//console.log(tokenData);
					}
				},
			});
		},
	}
}

</script>

<style>
	.all-date{
		width: 50%;
		float: left;
		font-size: 0.8rem; 
	}
	button{
	color: #ffffff;
	background-color: #6d1c79;
	}
	.appointment{
		width: 20%;
	font-size: 12px;
	line-height: 30px;
	padding: 0 8px !important;
	height: 30px;
	float: right;
	margin-bottom: 5px;
	}
	.appointment2{
		width: 20%;
		font-size: 12px;
		line-height: 30px;
		padding: 0 8px !important;
		height: 30px;
		background: #4E4B46;
		float: right;
		margin-bottom: 5px;
	}
	.nane{
	float: left;
	width:65%;
	font-size: 14px;
	line-height: 30px;
	margin-left: 5%;
	}
	.nane input{border: 1px solid #ccc;}
	span.title-left {
		margin-right: 10px;
		
		font-weight: bold;
	}
	.nane-small{
		float: left;
		width:40%;
		font-size: 12px;
		line-height: 30px;
		margin-left: 5%;
	}
	.time{  margin-left:5%;  float: left;font-size: 14px;
	}
	.img-avatar{
		width: 25%;
		border-radius: 50%;
		float: left;
	}
	.list{
		width: 92%;
		margin: 2%;
		display: inline-block;
		border: 1px solid #e5e5e5;
		background: #fff;
		font-size: 0.8rem;
		border-radius: 5px;
	    padding: 2%;
		margin-bottom: 1rem;
	}
	.no-img {
		    width: 70%;
		    float: left;
		    line-height: 30px;
		    font-size: 14px;
		    margin-left: 30px;
	}
	.no-img-title {
		float:left;
	}
	.no-img .upload-btn{
	    width: 75px;
	    height: 30px;
	    line-height: 30px;
	    float: left;
	    margin-left: 10px;
	    font-size: 14px;
	}
	.upload-continue {
		padding: 0 8px;
		height: 35px;
		line-height: 35px;
		font-size: 14px;
		width: 100px;
		margin: 0;
	}
	.ref-img-list {
		padding-top: 5px;
		clear: both;
	}
	.title_info {
		font-size: 16px;
		margin-bottom: 10px;
		display: block;
	}
	.upload-info button{width: 47%; float:left; margin: 3% 1.5%;}
	.picBoxShow{position: relative;
	    display: inline-block;
		width: 98%;margin:2% auto; text-align: center;}
	.picBoxShow img{max-width: 100%;}
	.picBox{position: relative;
		width: 46%;margin:2%;float:left;
	}
	.picBox img{max-width: 100%;max-height: 200px;}
	.picBox .remove-pic,
	.picBoxShow .remove-pic{
		position: absolute;
		top: 0;
		right: 0;
		width: 25px;
		height: 25px;
		font-size: 16px;
		line-height: 25px;
		text-align: center;
		color: #fff;
		background: #00C971;	
	}
	.service-continue-upload {
		width: 93%;
		display: flex;
		align-items: center;
	}
</style>
